/**
 * 
 */
package com.et114.modules.org.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.acegi.Constants;
import com.et114.components.acegi.cache.AcegiCacheManager;
import com.et114.components.ectable.EXTableUtils;
import com.et114.components.ectable.EctableConverts;
import com.et114.components.ectable.MultipleSelectedCell;
import com.et114.components.tree.tree51.BaseTree51Model;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.exception.CheckException;
import com.et114.core.utility.ArgumentTokenizer;
import com.et114.core.utility.GetterUtil;
import com.et114.core.utility.StringPool;
import com.et114.modules.org.form.FuncForm;
import com.et114.modules.org.message.FuncMessageManager;
import com.et114.modules.org.message.OrgMessageManager;
import com.et114.modules.org.services.FunctionManager;
import com.et114.modules.org.services.GroupManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.services.RoleManager;
import com.et114.modules.org.utility.MenuUtils;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.utility.tree.OrgGroupTree;
import com.et114.modules.org.vo.AclVo;
import com.et114.modules.org.vo.FuncRoleRelVo;
import com.et114.modules.org.vo.FunctionVo;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;

import org.apache.commons.beanutils.PropertyUtils;
import java.lang.reflect.InvocationTargetException;

import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
/*
 * @author guanhw
 */
public class FuncAction extends BaseDispatchAction {
	public static String URL_ = "" ; 
	private final String VALID_GROUPS_KEY = "__fw_groupMap"  ;
	private final String GROUPS_KEY = "__fw_groups"  ;

	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward generFuncsMenu( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		URL_ = request.getContextPath ( ) + "/func.go?method=go&funcId=" ;
		
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		if ( currentUser == null ) return new ActionForward( "/logout.go" , true ) ;
		
		Map urls = currentUser.getFuncs ( ) ; 
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;

		long ct = System.currentTimeMillis ( ) ;
		List funcs = fm.getFuncsList (  currentUser.getUserId ( ) ) ;
		logger.info ( "get menu data time:" + ( System.currentTimeMillis ( ) - ct ) + "ms" )  ;
		ct = System.currentTimeMillis ( ) ;
		MenuUtils mu = new MenuUtils();
		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( )  ; ) {
			FunctionVo func = ( FunctionVo )  iter.next ( )   ; 
			fm.up( func , mu ) ;
		}
		List roots = mu.getRoots ( ) ;
		Map allfuncs = mu.getFuncs ( ) ; 
		urls.putAll ( allfuncs ) ; 
		logger.info ( "count menu time:" + ( System.currentTimeMillis ( ) - ct ) + "ms" )  ;
		ct = System.currentTimeMillis ( ) ;
		String menu = fm.generateMenu ( roots  ) ; 
		logger.info ( "generate menu time....." + ( System.currentTimeMillis ( ) - ct )  + "ms" ) ;
		request.setAttribute ( "roots" , roots ) ;
		request.setAttribute ( "menu" , menu ) ;
		return mapping.findForward ( "generateMenu" ) ;
	}
	
	
	/**
	 * JQUERY AJAX 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward generFuncsDHtmlMenu( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		java.io.PrintWriter writer = response.getWriter ( ) ;
		
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		Map urls = currentUser.getFuncs ( ) ; 
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;

		//generate menu
		long ct = System.currentTimeMillis ( ) ;
		List funcs = fm.getFuncsList (  currentUser.getUserId ( ) ) ;
		logger.info ( "get menu data time:" + ( System.currentTimeMillis ( ) - ct ) + "ms" )  ;
		ct = System.currentTimeMillis ( ) ;
		MenuUtils mu = new MenuUtils();
		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( )  ; ) {
			FunctionVo func = ( FunctionVo )  iter.next ( )   ; 
			fm.up( func , mu ) ;
		}
		
		List roots = mu.getRoots ( ) ;
		StringBuffer menusb = new StringBuffer( ) ;
		fm.appendBeginRootDHTMLTree ( menusb ) ; 
		for ( java.util.Iterator iter = roots.iterator ( ) ; iter.hasNext ( ) ;  ) 
			fm.appendDHTMLTree ( ( ( FunctionVo )  iter.next ( ) ) , menusb ) ; 
		fm.appendEndRootDHTMLTree ( menusb )  ;
		
		//write session
		Map allfuncs = mu.getFuncs ( ) ; 
		urls.putAll ( allfuncs ) ; 
		//response client
		writer.write ( menusb.toString ( ) ) ; 
		writer.flush ( ) ;
		return null ; 
	}	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward generFuncsTree( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		HttpSession session = request.getSession ( ) ;
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;

		//
		Long funcId = ff.getFuncId ( );
		//
		//vaild
		
		Object path = session.getAttribute (  "locValue"  ) ;
		List els  ;
		String thtml ;
		//session
		ff.setCrtUser ( currentUser.getUserId ( ) ) ;
		//
		boolean isRoot = true ; 
		if ( funcId != null && funcId.longValue ( ) != 0 ) {
			els = fm.getChilds ( funcId ) ;
			if (  Constants.ROLE_TYPE_ORG_MANAGER ==  currentUserMaxRoleType && authTypes.size ( ) == 2 )  {
				MenuUtils mu = ( MenuUtils )session.getAttribute ( "mu__" ) ; 
				for ( java.util.Iterator iter = els.iterator ( ) ; iter.hasNext ( )  ; ) {
					FunctionVo func = ( FunctionVo )  iter.next ( )   ; 
					if ( !mu.containsKey ( func.getFuncId ( ) ) ) iter.remove ( ) ; 
				}							
			}
			isRoot = false ; 
		}
		else {
			els = fm.getRoots ( ) ;
			//filter 
			
			if (  Constants.ROLE_TYPE_ORG_MANAGER ==  currentUserMaxRoleType && authTypes.size ( ) == 2 )  {
				session.removeAttribute ( "mu__" ) ;
				List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
						Constants.ROLE_TYPE_ORG_MANAGER ,
						currentUser.getUserId ( ) );
				if ( roles.size ( ) > 0 ) {
					Long[] roleIds = new Long[ roles.size ( ) ] ; 
					for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
						RoleVo role = ( RoleVo ) roles.get ( i ) ;
						roleIds[ i ] = role.getRoleId ( ) ;
					}
					if ( roleIds.length > 0 )  {
						FuncRoleRelVo funcRoleRel = new FuncRoleRelVo( ) ;
						funcRoleRel.setRoleIds ( roleIds ) ; 
						List funcs = fm.getFuncByRole4fNp( funcRoleRel ) ; 
						MenuUtils mu = new MenuUtils();
						for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( )  ; ) {
							FunctionVo func = ( FunctionVo )  iter.next ( )   ; 
							fm.up( func , mu ) ;
						}
						// check 
						els = mu.getRoots ( ) ; 
						session.setAttribute ( "mu__" , mu ) ; 
					}
				} 			
			}
		}
		
		thtml = generateFuncTreeStr ( fm , !isRoot , els , ( path != null ? path
				.toString ( ) : null ) , request.getLocale ( )  );
		if ( path != null   ) request.setAttribute ( "nt" , "nt" ) ;
		//if ( els.size ( ) == 0   ) request.setAttribute ( "nt" , "nt" ) ;
		request.setAttribute (  "thtml"  , thtml ) ;
		request.setAttribute ( "defaultTabName" , FuncMessageManager.get ( request.getLocale ( )  ).getMessage ( "func.tree.root" )  ) ; 
		return mapping.findForward ( "genTree" ) ;
	}
		
	
	

	private String generateFuncTreeStr ( FunctionManager funcManager , boolean isLeaf , List list ,
			String path , java.util.Locale locale ) throws CheckException {
		String funcRootText = FuncMessageManager.get ( locale ).getMessage ( "func.tree.root" ) ;
		BaseTree51Model tree51Model = new BaseTree51Model( ) ; 
		tree51Model.setRootHref ( "func.go?method=toFuncTabs" ) ; 
		tree51Model.setBaseName ( funcRootText ) ; 
		tree51Model.setSrc( "func.go?method=generFuncsTree" ) ;
		tree51Model.setHref ( "func.go?method=toFuncTabs&" ) ; 
		tree51Model.setChildNodes (  list  ) ; 
		tree51Model.setTarget ( "frmRight" ) ;
		tree51Model.setLocValue ( path ) ; 
		tree51Model.setIsTarget ( BaseTree51Model.IS_TARGET_N ) ; 
		tree51Model.setRoot ( !isLeaf ) ;
		tree51Model.setTxtOnclick ( "initTree51Node( this )" ) ; 
		return OrgFactory.getFunctionManager ( ).generateFuncTreeStr( tree51Model ) ;
	}

	/**
	 * load org sub tree by grpId for title auths
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadChildTree ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		Long grpId = ff.getGrpId ( ) ;
		String thtml = null ;
		if ( grpId != null && grpId.longValue ( ) != 0L ){
			List cgs = OrgFactory.getGroupManager ( ).getChildGroup ( grpId ) ; 
	    	OrgGroupTree orgGroupTree = new OrgGroupTree( ) ; 
	    	orgGroupTree.setBaseName ( FuncMessageManager.get ( request.getLocale ( ) ).getMessage ( "func.tree.root" ) ) ;
	    	orgGroupTree.setSrc ( "func.go?method=loadChildTree&" ) ; 
	    	orgGroupTree.setRoot ( false ) ;
	    	orgGroupTree.setChildNodes (  cgs ) ;
	    	orgGroupTree.setTxtOnclick ( "__txtonclick( this )" ) ;
	    	thtml = OrgFactory.getGroupManager ( ).generateGroupTreeStr( orgGroupTree ) ;	
		}
    	
		request.setAttribute (  "thtml"  , thtml ) ;
		return mapping.findForward ( "genTree" ) ;
	}

	private List loadFuncsWithCountRel( FuncForm ff , FunctionManager fm ) throws Exception  {
		Long funcId = ff.getFuncId ( );
		List els  ;
		//session
		//
		if ( funcId != null && funcId.longValue ( ) != 0 ) els = fm.getChildsWithCountRel ( funcId ) ;
		else els = fm.getRootsWithCountRel ( ) ; 
		return els ; 
	}	
	
	
	private List loadFuncs( FuncForm ff , FunctionManager fm ) throws Exception  {
		Long funcId = ff.getFuncId ( );
		List els  ;
		//session
		//
		if ( funcId != null && funcId.longValue ( ) != 0 ) els = fm.getChilds ( funcId ) ;
		else els = fm.getRoots ( ) ;
		return els ; 
	}
	
	
	public  ActionForward toFuncTabs(  ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		HttpSession session = request.getSession ( ) ; 
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		//
		Long funcId = ff.getFuncId ( );
		
		request.getSession ( ).removeAttribute (  "funcNavs"  ) ;
		if ( funcId != null && funcId.longValue ( ) != 0  ) {
			StringBuffer navs = new StringBuffer();
			FunctionVo func = fm.getFunc ( funcId ) ; 
			//check;
			Object obj = session.getAttribute ( "mu__" ) ;
			if ( obj != null ) {
				MenuUtils mu = ( MenuUtils ) obj ; 
				if ( !mu.containsKey ( funcId ) ) 
					throw new Exception( Constants.AUTH_ACCESSDENIED ) ;  
			}
			
			//vaild 检查菜单是否为空
			if ( func == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}
			String paths = GetterUtil.get ( func.getPath ( ) , null ) ; 
			if ( paths != null && paths .indexOf ( FunctionManager.pathSplit ) > 0 ) {
				String[] seps = paths.split ( FunctionManager.pathSplit  ) ;
				List funcs = fm.loadFunctionsByIds ( seps ) ;
				for ( int i = 0 ; i < funcs.size()  ; i ++   ) {
					FunctionVo __dt = ( FunctionVo )  funcs.get ( i ) ; 
					if ( __dt != null ) {
						navs.append ( __dt.getFuncChn ( ) ) ; 
						if ( funcs.size() - 1 != i )
							navs.append ( StringPool.FORWARD_SLASH ) ;										
					}
				}
				paths = paths.replaceAll ( FunctionManager.pathSplit , StringPool.COMMA ) ;				
			}
			else 
				navs.append ( fm.getFunc ( Long.valueOf ( paths.trim ( ) ) ).getFuncChn ( ) ) ; 
			request.setAttribute ( "funcIsLeaf" , String.valueOf ( func.isLeaf ( ) ) ) ; 
			request.getSession ( ).setAttribute ( "funcNavs"  , navs.toString ( ) ) ; 
			request.getSession ( ).setAttribute ( BaseTree51Model.LOC_VALUES  , paths ) ; 
		}
		else request.getSession ( ).setAttribute ( BaseTree51Model.LOC_VALUES  , "-1" ) ;
		return mapping.findForward ( "toFuncTabs" ) ;
	}
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadFuncs( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long fct = System.currentTimeMillis ( ) ; 
		HttpSession session = request.getSession ( ) ; 
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		Long fid = ff.getFuncId ( ) ;
		if ( fid != null && fid.longValue ( ) != 0L ) {
			//vaild  检查菜单是否为空
			if ( fm.getFunc ( fid ) == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}
		}

		List els = loadFuncsWithCountRel( ff , fm ) ; 
		if (  Constants.ROLE_TYPE_ORG_MANAGER ==  currentUserMaxRoleType && authTypes.size ( ) == 2 )  {
			MenuUtils mu = ( MenuUtils )session.getAttribute ( "mu__" ) ; 
			for ( java.util.Iterator iter = els.iterator ( ) ; iter.hasNext ( )  ; ) {
				FunctionVo func = ( FunctionVo )  iter.next ( )   ; 
				if ( !mu.containsKey ( func.getFuncId ( ) ) ) iter.remove ( ) ; 
			}							
		}		
		request.setAttribute (  "funcs"  , els ) ;
		request.setAttribute ( "elssize" , new Integer( els.size ( ) ) ) ; 
		logger.info ( "load funcs time :" + ( System.currentTimeMillis ( ) - fct ) ) ;
		return mapping.findForward ( "toFuncs" ) ;
	}	
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadFuncsAssembler( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		return mapping.findForward ( "toFuncs" ) ;
	}
	

	
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadSubFuncs( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		return loadFuncs( mapping , form , request , response ) ;
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws CheckException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws CacheException 
	 * @throws Exception
	 */
	public  ActionForward addFunc( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception  {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		FuncForm ff = ( FuncForm ) form;
		
		//vaild
		
		String url = ff.getUrl ( ) ; 
		String res = null ; 
		if ( url != null && !Constants.NULL_URL .equals ( url.trim ( ) ) && !"".equals ( url.trim ( ) )   ){
			res = AcegiCacheManager.getInstansce ( ).cacheAntContains ( url ) ; 
			if ( res != null ) {
				Error error = new Error ( );
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.funcurl.exist" ,request.getLocale ( )   ) ); 
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY ,	error );
			}			
		}

		//
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		FunctionVo vo = new FunctionVo();
		vo.setOperUser ( currentUser.getUserId ( ) ) ; 
		//get params
		Long ffuncId = ff.getFfuncId ( ); 

		String path = GetterUtil.get (  ff.getPath ( ) , null ) ; 
		if ( path != null  ) { // update
			ff.setUpdtUser ( currentUser.getUserId ( ) ) ;
			PropertyUtils.copyProperties ( vo , ff ) ;
			FunctionVo funcvo = fm.getFunc ( vo.getFuncId ( ) );
			// vaild 检查菜单是否为空
			if ( funcvo == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}

			if ( ! funcvo.getUrl ( ).equals ( url ) && res != null ) return mapping.findForward ( "glerror" );		
			if ( ! funcvo.getFuncChn ( ).equals ( vo.getFuncChn ( ) ) ) {
				if ( ( fm.getcountFuns ( vo ) ).longValue ( ) > 0 ) {
					Error error = new Error ( );
					error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.funcname.already.exist" ,request.getLocale ( )   ) );
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY ,	error );
					return mapping.findForward ( "glerror" );
				}
			}
			fm.updateFunc ( vo ) ;
			StringBuffer to = new StringBuffer( "funcSuccess.go?type=updatefunc" ) ;
			to.append ( "&funcId=" ).append ( vo.getFuncId ( ) ) ;
			return new ActionForward( to.toString ( ) , true ) ; 
		}
		else { //new 
			//vaild
			if ( res != null ) return mapping.findForward ( "glerror" );
			
			ff.setCrtUser ( currentUser.getUserId ( ) ) ;
			ff.setLeaf ( true ) ;	
			PropertyUtils.copyProperties ( vo , ff ) ;
			if ( ( fm.getcountFuns ( vo ) ).longValue ( ) > 0 ) {
				Error error = new Error ( );
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.funcname.already.exist" , request.getLocale ( )  ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error );
				return mapping.findForward ( "glerror" );
			}
			// vaild 检查菜单是否为空
			if ( vo.getFfuncId ( ) != null && vo.getFfuncId ( ).longValue ( ) != 0L ) {
				if ( fm.getFunc ( vo.getFfuncId ( ) ) == null  ) {
					error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;								
				}		
			}
			
			fm.addFunc ( vo ) ;	
			StringBuffer to = new StringBuffer( "funcSuccess.go?type=func" ) ;
			if ( ffuncId != null && ffuncId.longValue ( ) != 0 ) {
				to.append ( "&ffuncId=" ).append ( ffuncId ) ;
			}
			return new ActionForward( to.toString ( ) , true ) ; 
		}
	}
 
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return<c:out value="${ecAct}"/>
	 * @throws Exception
	 */
	public  ActionForward loadFunc( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		
		Long id = ff.getFuncId ( ) ; 
		if ( id != null && id .longValue ( ) != 0L ) {
			FunctionVo vo = fm.getFunc ( id ) ; 
			// vaild 检查菜单是否为空
			if ( vo == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}					
			request.setAttribute ( "funcVo" , vo ) ;
		}
		return mapping.findForward ( "toModFuncns" ) ;
	}
	
	
	public  ActionForward removeFunc( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception  {
		StringBuffer  to = new StringBuffer( "func.go?method=loadFuncs&m=0" ) ;
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		Long funcId = ff.getFuncId ( );
		if ( funcId != null &&  funcId.longValue ( ) != 0 ) 
			to.append ( "&funcId=" ).append ( funcId ) ;

		String params = EXTableUtils.getLimitParams ( request  ) ;
		to.append ( params ) ;
		Long[] deleteIds = ff.getDeleteId ( ) ;
		if ( deleteIds != null ) {
			for ( int i = 0 ; i < deleteIds.length ; i ++ ) {
				Long deleteId = deleteIds[ i ] ;
				fm.deleteFunc (   deleteId ,  getCurrentUser ( request ).getUserId ( ) ) ;
			}
		}
		return new ActionForward( to.toString ( ) , true  );
	}
  
	
	public  ActionForward toOrderFuncs( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		List els = loadFuncs( ff , fm ) ; 
		request.setAttribute (  "funcs"  , els ) ;
		return mapping.findForward ( "toOrderFuncs" ) ;
	}
	
	/**
	 * TODO 改为数据库端循环更新
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @throws CacheException 
	 */
	public  ActionForward orderFuncs( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		StringBuffer  to = new StringBuffer( "func.go?method=toOrderFuncs" ) ;
		//
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		Long funcId = ff.getFuncId ( );
		long funcNo = 0;
		if ( funcId != null && funcId .longValue ( ) != 0 ) {
			// 
			if ( fm.getFunc ( funcId ) == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}					

			funcNo = funcId.longValue ( ) * fm.getmSpil ( ) ; 
			to.append ( "&funcId=" ).append ( funcId ) ;
		}
		String orders = ff.getOrders ( ) ;
		if ( orders != null ) {
			StringTokenizer st = new StringTokenizer( orders , StringPool.SEMICOLON ) ;
			int count = st.countTokens ( ) ; 
			for (  int i = 0 ; i <  count ; i ++ ) {
				Long orderId = Long.valueOf ( st.nextToken() );
				FunctionVo vo = fm.getFunc ( orderId ) ; 
				if ( funcId != null && funcId .longValue ( ) != 0 ) { 
					// has parent node
					funcNo ++ ;  
					vo.setFuncNo ( new Long( funcNo  ) ) ;
				}
				else {
					long ss = ( i + 1 ) * fm.getmSpil ( ) ;
					vo.setFuncNo ( new Long ( ss  ) ) ;
				}
					
				fm.updateFunc ( vo ) ;
			}
		}
		to.append ( "&m=0" );
		return new ActionForward( to.toString ( ) , true  );
	}
	
	
	/**
	 * 生成授权首页 
	 */
	public  ActionForward indexRoleAuths ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
			List soptions = OrgFactory.getRoleManager ( ).getRoleTypes ( )  ;
			request.setAttribute ( "options" , soptions ) ;	
			return mapping.findForward (  "indexRolesAuths"  ) ;
	}	
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		String _m = request.getParameter ( "_m" ) ; 
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		
		if ( _m == null || "".equals ( _m.trim ( ) ) ) {
			if ( authTypes.size ( ) > 0 ) _m = ( ( BizOption ) authTypes.get ( 0 ) ).getOptionValue ( ) ;
		}
		if ( authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
			_m = Constants.RESOURCE_DO_AUTH_TITLE ; 
			List tmpAt = new ArrayList( 0 ) ; 
			tmpAt.addAll ( authTypes ) ; 
			for ( java.util.Iterator iter = tmpAt.iterator ( ) ; iter.hasNext ( ) ;  ) {
				String v = ( ( BizOption ) iter.next ( ) ).getOptionValue ( );
				if ( v .equals ( Constants.RESOURCE_DO_AUTH_ROLE ) ) 
					iter.remove ( ) ; 
			}		
			request.setAttribute ( "authTypes" , tmpAt ) ;
		}	
			
				
		Long funcId = ff.getFuncId ( );
		List ls = new ArrayList();
		
		FunctionVo vo = new FunctionVo( ) ;
		PropertyUtils.copyProperties ( vo , ff ) ; 
		if ( funcId != null && funcId .longValue ( ) != 0 ) {
			vo.setRoleType ( currentUserMaxRoleType ) ;
			if ( Constants.RESOURCE_DO_AUTH_USER.equals ( _m ) ) { //user
				ls = fm.getUsersByFunc ( vo ) ;
			}
			else if ( Constants.RESOURCE_DO_AUTH_ROLE.equals ( _m ) ) { //role
		        //set convert
		        EctableConverts  ec = vo.getEconverts ( ) ; 
		        ec.setProConvert ( "authDate" , "a.crtTime" ) ;
		        ec.setProConvert ( "roleName" , "b.roleName" ) ;
		        
				EXTableUtils.initLimitPage(  vo , request ) ;
				Long rl = fm.countgetGreaterRolesByFunction ( vo ) ;
				vo.setTotalRows ( rl.intValue ( ) ) ; 
				EXTableUtils.setLimitRowAttributes(  vo , request ) ;
				ls = fm.getGreaterRolesByFunction ( vo , CONST.PAGE  ) ;

				if ( vo.getRoleName ( ) != null ) request.setAttribute ( "roleName" , vo.getRoleName ( ) ) ;
				if ( vo.getStartTime ( ) != null ) request.setAttribute ( "startTime" , vo.getStartTime ( ) ) ;
				if ( vo.getEndTime ( ) != null ) request.setAttribute ( "endTime" , vo.getEndTime ( ) ) ;
			}
			else if ( Constants.RESOURCE_DO_AUTH_TITLE.equals ( _m ) ) { //title
				Long grpId = ff.getGrpId ( ) ; 
				Map groupMap = new HashMap( ) ; 
				Map roots = new HashMap( ) ; 
				long ct = System.currentTimeMillis ( ) ; 
				GroupManager groupManager = OrgFactory.getGroupManager ( );
				List groups = new ArrayList( 0  )  ;
				
				groups.addAll ( (  request.getSession ( ).getAttribute (  GROUPS_KEY  ) != null  ? ( List ) request.getSession ( ).getAttribute (  GROUPS_KEY  ) : new ArrayList( ) ) ) ;
				groupMap.putAll ( (  request.getSession ( ).getAttribute (  VALID_GROUPS_KEY  ) != null  ? ( Map ) request.getSession ( ).getAttribute (  VALID_GROUPS_KEY  ) : new HashMap() )  ) ;
	
			
				if ( authTypes.size ( ) == 2   ) { // role title
					if ( currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER
							&& ( groups.size ( ) == 0 || groupMap.size ( ) == 0 ) ) {
			
						List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
								Constants.ROLE_TYPE_ORG_MANAGER ,
								currentUser.getUserId ( ) );
						if ( roles.size ( ) > 0 ) {
							StringBuffer roleIds = new StringBuffer() ;
							for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
								RoleVo role = ( RoleVo ) roles.get ( i ) ;
								roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
								if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
							}
							
							if ( roleIds.length ( ) > 0 ) {
								roots = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
								groupMap.putAll ( roots ) ; 
								groups.addAll ( OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( roots ) ) ; 
							}							
						} 		
					}
					else if ( currentUserMaxRoleType < Constants.ROLE_TYPE_ORG_MANAGER ) 
						groups.add ( groupManager.loadGroup4SelectOption ( grpId )  ) ;
				}
				else  throw new Exception( Constants.AUTH_ACCESSDENIED ) ;  
					
				GroupVo groupVo = null ; 
				if (  ( authTypes.size ( ) == 2 && ( grpId == null  ) ) ) {
					groupVo = ( GroupVo )groups.get ( 0 ) ; 
					groupVo.setFgrpId ( null ) ;
				}
				else {
					groupVo = groupManager.loadGroup4SelectOption ( grpId ) ;
					//check
					if (  authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
						if ( groupMap != null && !groupMap.containsKey ( groupVo.getGrpId ( ) ) ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ;
						if ( roots.containsKey ( groupVo.getGrpId ( ) ) ) groupVo.setFgrpId ( null ) ;
					}						
				}
				
			
				
				
				ls = groupVo.getTitleList ( );
				List selectedTitleList = fm.getTitlesByFunc ( vo ); // TODO
				StringBuffer sb = new StringBuffer( StringPool.SEMICOLON ) ; 
				for ( java.util.Iterator iter = selectedTitleList.iterator ( ) ; iter.hasNext ( ) ;  ) {
					TitleMsgVo title = ( TitleMsgVo ) iter.next ( ) ;
					Long id = title.getTitleId ( ) ;
					java.util.Date authDate = title.getAuthDate ( ) ; 
					for ( java.util.Iterator _iter = ls.iterator ( ) ; _iter.hasNext ( ) ;  )   {
						title = ( TitleMsgVo ) _iter.next ( ) ;
						if ( title.getTitleId ( ).equals ( id ) ) {
							title.setAuthDate ( authDate ) ;
							sb.append ( title.getTitleId ( ) ).append ( StringPool.SEMICOLON )  ;
							break ;
						}
					}
				}
				
				//
				boolean mark = false ; 
				for ( java.util.Iterator iter = groups.iterator ( ) ; iter.hasNext ( ) ;  ) {
					GroupVo group__ = ( GroupVo ) iter.next ( ) ;
					if ( group__.getGrpId ( ).equals (  groupVo.getGrpId ( ) ) ) {
						iter.remove ( ) ;
						mark = true ; 
						break ; 
					}
					else mark = false ; 
				}
				if ( mark == false  ) groups.clear ( ) ;  
				
				request.setAttribute ( "groups" , groups ) ; 
				request.setAttribute ( "groupVo" , groupVo );
				request.setAttribute (	MultipleSelectedCell.SELECTED_PRESIDENTS ,	sb.toString ( ) );
				logger.info ( "load title auths ." +  ( System.currentTimeMillis ( ) - ct  ) ) ;
			}
		}
		
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		request.setAttribute ( "ls" , ls ) ; 
		request.setAttribute ( "_m" , _m ) ;
		
		//TODO second判断分散岗位授权
		String titleForward = "/modules/system/funcAuthsTitles.jsp"; // title
																		// forward
		
		if ( request.getAttribute ( "authTypes" ) == null )
			request.setAttribute ( "authTypes" , authTypes );
		else if ( request.getParameter ( "second" ) == null ) {
			titleForward = "/func.go?method=loadTitleAuthsIndex&_m=title&funcId="
					+ ff.getFuncId ( );
		}
		
		titleForward = response.encodeURL (  titleForward ) ;
		if ( Constants.RESOURCE_DO_AUTH_TITLE.equals ( _m ) ) return new ActionForward( titleForward ) ; 
		
		return mapping.findForward ( "loadAuths" ) ;
	}

	

	
	
	public  ActionForward loadTitleAuthsIndex( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {

		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		String _m = request.getParameter ( "_m" ) ; 
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		
		if ( _m == null || "".equals ( _m.trim ( ) ) ) {
			if ( authTypes.size ( ) > 0 ) _m = ( ( BizOption ) authTypes.get ( 0 ) ).getOptionValue ( ) ;
		}
		if ( authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
			_m = Constants.RESOURCE_DO_AUTH_TITLE ; 
			List tmpAt = new ArrayList( 0 ) ; 
			tmpAt.addAll ( authTypes ) ; 
			for ( java.util.Iterator iter = tmpAt.iterator ( ) ; iter.hasNext ( ) ;  ) {
				String v = ( ( BizOption ) iter.next ( ) ).getOptionValue ( );
				if ( v .equals ( Constants.RESOURCE_DO_AUTH_ROLE ) ) 
					iter.remove ( ) ; 
			}		
			request.setAttribute ( "authTypes" , tmpAt ) ;
		}	
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		if ( request.getAttribute ( "authTypes" ) == null ) request.setAttribute ( "authTypes" , authTypes ) ;

		return new ActionForward( "/modules/system/funcAuthsTitleIndex.jsp" ) ; 
	}
	
	
	public ActionForward loadChildGroups( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
			FuncForm ff = ( FuncForm ) form;
			Long grpId = ff.getGrpId ( ) ; 
			GroupManager groupManager = OrgFactory.getGroupManager ( );
			List groups = groupManager.getChildGroup ( grpId ) ; 
			String tree = OrgFactory.getFunctionManager ( ).generateGroupTreeStr (  true , groups ,
					String.valueOf ( grpId ) , BaseTree51Model.IS_TARGET_Y , request.getLocale ( ) ,
					ff.getFuncId ( ) );
			request.setAttribute ( "partyTree" , tree ) ; 
			
			return new ActionForward( "/modules/org/partyTree.jsp" ) ;
	}
	
	
	
	
	public ActionForward loadTitleAuthsGroups( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		    //
		    request.getSession ( ).removeAttribute (  VALID_GROUPS_KEY  ) ;
		    request.getSession ( ).removeAttribute (  GROUPS_KEY  ) ;
		    
			FuncForm ff = ( FuncForm ) form;
			SessionUserInfo currentUser = getCurrentUser ( request ) ;
			byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
			Map groupMap = new HashMap( ) ; 
			Map roots = new HashMap( ) ; 

			GroupManager groupManager = OrgFactory.getGroupManager ( );
			List groups = new ArrayList( 0  )  ;


			if ( currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER  ) {
				List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
						Constants.ROLE_TYPE_ORG_MANAGER ,
						currentUser.getUserId ( ) );
				if ( roles.size ( ) > 0 ) {
					StringBuffer roleIds = new StringBuffer() ;
					for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
						RoleVo role = ( RoleVo ) roles.get ( i ) ;
						roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
						if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
					}
					
					if ( roleIds.length ( ) > 0 ) {
						roots = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
						groupMap.putAll ( roots ) ; 
						groups.addAll ( OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( roots ) ) ;
						request.getSession ( ).setAttribute ( VALID_GROUPS_KEY , groupMap ) ; 
					}							
				} 		
			}
			else if ( currentUserMaxRoleType < Constants.ROLE_TYPE_ORG_MANAGER ) 
				groups.add ( groupManager.loadGroup4SelectOption ( new Long ( Constants.ORG_GROUP_BASE_VALUE ) )  ) ;
			
			
			request.getSession ( ).setAttribute ( GROUPS_KEY , groups ) ; 
			
			String cugid = ( ( GroupVo ) groups.get ( 0 ) ).getGrpId ( ).toString ( ) ;
			String tree = OrgFactory.getFunctionManager ( ).generateGroupTreeStr(  false , groups , cugid , BaseTree51Model.IS_TARGET_Y , request.getLocale ( ) , ff.getFuncId ( ) ) ; 
			request.setAttribute ( "partyTree" , tree ) ; 
			
		

			return new ActionForward( "/modules/org/partyTree.jsp" ) ;
	}

	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadRolesAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		
		Long funcId = ff.getFuncId ( );
		List ls = new ArrayList();
		if ( funcId != null && funcId .longValue ( ) != 0 ) {
			FunctionVo vo = fm.getFunc ( funcId ) ;
			if ( vo == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}					

			vo.setRoleType ( ff.getRoleType ( ) ) ;
			ls = fm.getRolesByFunc ( vo ) ;
		}
		
		RoleManager roleManager = OrgFactory.getRoleManager ( ) ;
		List roles = roleManager.getRoles (  ff.getRoleType ( ) ) ; 
		request.setAttribute ( "roles" , roles ) ;
		request.setAttribute ( "ls" , ls ) ; 		
		return mapping.findForward ( "toRolesAuths" ) ;
	}

	/**
	 * ToDo
	 * @param mapping
	 * @throws Exception
	 */
	public  ActionForward doRoleAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception   {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		
		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		
		Long funcId = ff.getFuncId ( ); 
		String principalIds = ff.getPrincipalIds ( );
		
		//现有角色
		byte roleType = ff.getRoleType ( ) ;
		FunctionVo func = fm.getFunc ( funcId ) ; 
		// vaild 检查菜单是否为空
		if ( func == null  ) {
			error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
			request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
			return mapping.findForward( "glerror" ) ;								
		}					
		
		List allChilds = func.isLeaf ( ) ? new ArrayList( 0 ) : fm.getFuncsByPath ( func.getPath ( ) + StringPool.SLE ) ; 
		allChilds.add ( func ) ;
		if ( roleType != 0 ) 
			for ( java.util.Iterator iter = allChilds.iterator ( ) ; iter.hasNext ( ) ;  ) {
				FunctionVo child = ( FunctionVo ) iter.next ( ) ; 
				child.setRoleType ( roleType ) ; 
				child.setCrtUser ( currentUser.getUserId ( ) ) ; 
				fm.saveRoleAuthorize ( child , principalIds  ) ; // since 1.90
			}
		
		StringBuffer to = new StringBuffer() ; 
		to.append ( "func.go?method=loadRolesAuths" ).append ( "&funcId=" )
				.append ( funcId ).append ( "&roleType=" ).append ( roleType );
		return new ActionForward( to.toString ( ) , true ) ;
	}
	
	
	
	public ActionForward saveTitleAuths ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
		FunctionManager functionManager = OrgFactory.getFunctionManager ( ) ;
		GroupManager groupManager = OrgFactory.getGroupManager ( );
		
		FuncForm funcForm = ( FuncForm ) form;
		Long funcId = funcForm.getFuncId ( ) ;
		if ( funcId == null || funcId.longValue ( ) == 0 ) 
			throw new Exception( "funcId is null !" ) ;

		if ( funcForm.getGrpId ( ) == null || funcForm.getGrpId ( ).longValue ( ) == 0  ) 
			throw new Exception( "grpId is null !" ) ;
		
		FunctionVo functionVo = functionManager.getFunc ( funcId ) ; 
		// vaild 检查菜单是否为空
		if ( functionVo == null  ) {
			error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
			request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
			return mapping.findForward( "glerror" ) ;								
		}					
		
		String selecttitleIds = request.getParameter ( MultipleSelectedCell.SELECTED_PRESIDENTS ) ;
		List chkdTitleList = new ArrayList ( );
		if ( selecttitleIds != null && !selecttitleIds.trim ( ).equals ( StringPool.SEMICOLON ) ) {
			selecttitleIds = selecttitleIds.substring ( 1  , selecttitleIds.length ( ) - 1  ) ;
			ArgumentTokenizer at = new ArgumentTokenizer( selecttitleIds , StringPool.CHAR_SEMICOLON ) ; 
			int i = 0 ; 
			Long[] titleIds = new Long[ at.countTokens ( ) ] ; 
			while( at.hasNext ( ) ) {
				titleIds[ i ] = Long.valueOf ( at.next ( ) ) ; 
				i ++ ;
			}
			if ( titleIds .length > 0 )
				chkdTitleList.addAll ( groupManager.queryTitlesByIds( titleIds ) ) ;

		}
		List tmps = new ArrayList( 0 ) ; 
		List allChilds = functionVo.isLeaf ( ) ? new ArrayList( 0 ) : functionManager.getFuncsByPath ( functionVo.getPath ( ) + StringPool.SLE  ) ;  
		allChilds.add ( functionVo ) ; 
		for ( java.util.Iterator iter = allChilds.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FunctionVo child = ( FunctionVo ) iter.next ( ) ; 
			tmps.addAll ( chkdTitleList ) ;
			child.setTitles ( tmps ) ;
			child.setCrtUser ( currentUser.getUserId ( ) );
			functionManager.saveTitleAuths ( funcForm.getGrpId ( ) , child ) ; // since 1.90
			tmps.clear ( ) ; 
		}
		
		
		String params = EXTableUtils.getLimitPageParams ( request ) ;
		StringBuffer to = new StringBuffer() ; 
		to.append ( "func.go?method=loadAuths&second=y&_m=title" ).append ( "&funcId=" )
				.append ( functionVo.getFuncId ( ) ).append ( "&grpId=" ).append ( funcForm.getGrpId ( ) );
		to.append ( params ) ;
		return new ActionForward( to.toString ( ) , true ) ;
	}
    

	
	/**
	 * 批量
	 * @throws Exception
	 */

	/**
	 * @throws Exception
	 */
	public  ActionForward deleteAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception  {
		SessionUserInfo currentUser = getCurrentUser ( request );		
		StringBuffer to = new StringBuffer( "func.go?method=loadAuths&funcId=" ) ; 

		FuncForm ff = ( FuncForm ) form;
		FunctionManager fm = OrgFactory.getFunctionManager ( );
		
		String _m = request.getParameter ( "_m" ) ; 
		Long funcId = ff.getFuncId ( );
		Long [] ds = ff.getDeleteId ( ) ; 
		if ( funcId != null && funcId.longValue ( ) != 0 &&  ds != null ) {
				if ( Constants.RESOURCE_DO_AUTH_USER.equals ( _m ) ) { //user
				}
				else if ( Constants.RESOURCE_DO_AUTH_ROLE.equals ( _m ) ) { //role
					FunctionVo func = fm.getFunc ( funcId ) ;
					// vaild 检查菜单是否为空
					if ( func == null  ) {
						error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
						request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
						return mapping.findForward( "glerror" ) ;								
					}					
		
					//since 1.90
					List allChilds = func.isLeaf ( ) ?  new ArrayList( 0 ) : fm.getFuncsByPath ( func.getPath ( ) + StringPool.SLE ) ;  
					allChilds.add ( func ) ; 
					if ( ds != null )
						for ( java.util.Iterator iter = allChilds.iterator ( ) ; iter.hasNext ( ) ;  ) {
							FunctionVo child = ( FunctionVo ) iter.next ( ) ; 
							for ( int i = 0 ; i < ds.length ; i ++  ) {
								AclVo acl = new AclVo () ;
								acl.setOperUser ( currentUser.getUserId ( ) ) ; 
								acl.setResourceType ( Constants.RESOURCE_URL ) ;
								acl.setResourceId ( child.getFuncId ( ) ) ;
								Long roleId = ds[ i ] ; 
								acl.setPrincipalId ( roleId ) ; 
								acl.setPrincipalType ( Constants.PRINCIPALID_ROLE ) ;
								fm.deleteFuncAuthorize ( acl , true ) ; 
							}		
						}
				}
				else if ( Constants.RESOURCE_DO_AUTH_TITLE.equals ( _m ) ) { //title

				}			
		}
		to.append ( funcId ) ; 
		to.append ( "&_m=" ).append ( _m );
		String params = EXTableUtils.getLimitParams ( request ) ;
		to.append ( params ) ;
		return new ActionForward( to.toString ( ) , true ) ;
	}
	

	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward go( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		if ( currentUser == null ) return new ActionForward( "/logout.go" , true ) ;
		
		FuncForm ff = ( FuncForm ) form;
		//clear 
		//define by toTabs
		request.getSession ( ).removeAttribute (  BaseTree51Model.LOC_VALUES  ) ;
		currentUser.setCurrentLoc ( "" ) ;
		
		FunctionManager fm = OrgFactory.getFunctionManager ( );

		Long funcId = ff.getFuncId ( );
		String contextPath = request.getContextPath ( ) ; 
		String url = contextPath  ; 
		StringBuffer navs = new StringBuffer();
		Map funcs = currentUser.getFuncs ( );
		if ( funcs.containsKey (  funcId ) ) {
			FunctionVo vo = ( FunctionVo ) funcs.get ( funcId ) ; 
			url = vo.getUrl ( ) ; 

			if ( !url .startsWith ( Constants.NULL_URL ) )  url = Constants.NULL_URL + url ; 
			String paths = GetterUtil.get ( vo.getPath ( ) , null ) ; 
			if ( paths != null && paths .indexOf ( FunctionManager.pathSplit ) > 0 ) {
				String[] seps = paths.split ( FunctionManager.pathSplit  ) ;
				if ( seps != null && seps.length > 0 ) {
					List tmpfuncs = fm.loadFunctionsByIds( seps ) ; 
					for (  int i = 0 ; i < seps.length - 1 ; i ++ ) {
						Object obj = tmpfuncs.get ( i ) ; 
						if ( obj != null ) {
							navs.append ( ( ( FunctionVo ) obj ).getFuncChn ( ) ) ; 
							navs.append ( FunctionManager.pathSplit ) ;						
						}
					}					
				}
			}
			navs.append ( vo.getFuncChn ( ) ) ;
			currentUser.setCurrentLoc ( navs.toString ( ) ) ;
		}
		if ( url == null || Constants.NULL_URL.equals ( url.trim ( ) ) )   {
			error.setErrorTitle ( "URL is NULL !" );
			error.setGoBack ( false ) ; 
			request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
			return mapping.findForward( "glerror" ) ;								
		}
			
		return new ActionForward( url , true ) ;
	}
	

	//二级授权
	public  ActionForward loadFuncAuths4f( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		FuncForm ff = ( FuncForm ) form;
		FuncRoleRelVo funcRoleRel = new FuncRoleRelVo( ) ;
		PropertyUtils.copyProperties( funcRoleRel , ff ) ; 
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ; 
		if ( authTypes.size ( ) == 2 ) {
	        EctableConverts  ec = funcRoleRel.getEconverts ( ) ; 
	        ec.setProConvert ( "crtTime" , "a.crtTime" ) ;		
			EXTableUtils.initLimitPage(  funcRoleRel , request ) ;
			Long rl = fm.countgetRolesByFuncId4f ( funcRoleRel ) ;
			funcRoleRel.setTotalRows ( rl.intValue ( ) ) ; 
			EXTableUtils.setLimitRowAttributes(  funcRoleRel , request ) ;
			List roles = fm.getRolesByFuncId4f ( funcRoleRel ) ;
			request.setAttribute ( "roles" , roles ) ; 			
		}
		return mapping.findForward ( "toFuncRolesAuths4f" ) ;
	}
	
	public ActionForward toAuthIndex4f ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		BizOption bizOption = OrgFactory.getRoleManager ( ).getRoleType ( Constants.ROLE_TYPE_ORG_MANAGER )  ;
		request.setAttribute ( "option" , bizOption ) ;	
		return mapping.findForward ( "authIndex4f" );
	}

	public ActionForward loadFuncRoleAuths4f ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FuncRoleRelVo funcRoleRel = new FuncRoleRelVo( ) ;
		PropertyUtils.copyProperties( funcRoleRel , ff ) ; 
		
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		//load all roles
		if ( authTypes .size ( ) == 2 ) {
			RoleManager roleManager = OrgFactory.getRoleManager ( ) ;
			List roles = roleManager.getRoles ( Constants.ROLE_TYPE_ORG_MANAGER  ) ; 
			request.setAttribute ( "roles4f" , roles ) ;

			List funcRoles4f = OrgFactory.getFunctionManager ( ).getRolesByFunc4fNp ( funcRoleRel ) ;
			request.setAttribute ( "funcRoles4f" , funcRoles4f ) ;			
		}
		return mapping.findForward ( "roleAuth4f" );
	}
	
	public ActionForward doFuncRoleAuth4f ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );	
		FuncForm ff = ( FuncForm ) form;
		/*
		byte userRoleType = currentUser.getCurrentUserMaxRoleType ( ) ;
        if ( userRoleType != Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( "Access Denied!" ) ;   */
        byte roleType = ff.getRoleType ( ) ; 
		if (  Constants.ROLE_TYPE_ORG_MANAGER !=  roleType  ) 
			throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   

		FunctionManager fm = OrgFactory.getFunctionManager ( ) ; 
		FunctionVo func = fm.getFunc ( ff.getFuncId ( ) ) ;
		if ( func != null ) {
			List funcs = func.isLeaf ( ) ? new ArrayList( 0 ) : fm.getFuncsByPath( func.getPath ( ) + StringPool.SLE ) ;
			funcs.add ( func ) ; 
			for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
				func = ( FunctionVo  ) iter.next ( ) ; 
				fm.createFuncRoleRel4f( func.getFuncId ( ) , currentUser.getUserId ( ) ,  ff.getPrincipalIds ( ) ) ; 
			}			
		}
		StringBuffer sb = new StringBuffer( "func.go?method=loadFuncRoleAuths4f" ) ; 
		sb.append ( "&funcId=" ).append ( ff.getFuncId ( ) ) ; 
		sb.append ( "&roleType=" ).append ( roleType ) ;
		return new ActionForward( sb.toString ( ) , true ) ;
	}
	
	public  ActionForward removeFuncRoleAuth4f( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncForm ff = ( FuncForm ) form;
		FuncRoleRelVo funcRoleRel = new FuncRoleRelVo( ) ; 
		
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ; 
		FunctionVo func = fm.getFunc ( ff.getFuncId ( ) ) ;
		if ( func != null  ) {
			List funcs = func.isLeaf ( ) ? new ArrayList( 0 ) : fm.getFuncsByPath( func.getPath ( ) + StringPool.SLE ) ;
			funcs.add ( func ) ;
			Long[] deleteIds = ff.getDeleteId ( ) ; 
			if ( deleteIds != null ) 
				for ( int  i = 0  ; i < deleteIds.length ; i ++  )  {
					for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
						FunctionVo func_ = ( FunctionVo )  iter.next ( ) ; 
						funcRoleRel.setFuncId ( func_.getFuncId ( ) ) ;
						funcRoleRel.setRoleId ( deleteIds[ i ] ) ;
						fm.deleteFuncRoleRel ( funcRoleRel ) ; 
					}
				}			
		}
		StringBuffer sb = new StringBuffer( "func.go?method=loadFuncAuths4f" ) ; 
		sb.append ( "&funcId=" ).append ( ff.getFuncId ( ) ) ; 
		return new ActionForward( sb.toString ( ) , true ) ;
	}
	
}
